from datetime import datetime
from app import db


class User(db.Model):
    """小程序用户模型"""
    __tablename__ = 'user'
    
    id = db.Column(db.Integer, primary_key=True)
    openid = db.Column(db.String(100), unique=True, nullable=False, comment='微信openid')
    unionid = db.Column(db.String(100), comment='微信unionid')
    nickname = db.Column(db.String(100), comment='昵称')
    avatar = db.Column(db.String(255), comment='头像')
    gender = db.Column(db.Integer, default=0, comment='性别(0=未知,1=男,2=女)')
    phone = db.Column(db.String(20), comment='电话')
    birthday = db.Column(db.Date, comment='生日')
    status = db.Column(db.Boolean, default=True, comment='状态(True=启用,False=禁用)')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'openid': self.openid,
            'unionid': self.unionid,
            'nickname': self.nickname,
            'avatar': self.avatar,
            'gender': self.gender,
            'gender_text': self.get_gender_text(),
            'phone': self.phone,
            'birthday': self.birthday.strftime('%Y-%m-%d') if self.birthday else None,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None
        }
    
    def get_gender_text(self):
        """获取性别文本"""
        gender_map = {0: '未知', 1: '男', 2: '女'}
        return gender_map.get(self.gender, '未知') 